package com.xxx.lease.web.admin.service.impl;

import com.xxx.lease.common.minio.MinioProperties;
import com.xxx.lease.web.admin.service.FileUploadService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;

    @Override
    public String upload(MultipartFile file) {


        try{
            //检查桶是否存在
            boolean result = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if(!result){
                //不存在就创建新的桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());

                String policy = """
                         {
                          "Statement" : [ {
                            "Action" : "s3:GetObject",
                            "Effect" : "Allow",
                            "Principal" : "*",
                            "Resource" : "arn:aws:s3:::%s/*"
                          } ],
                          "Version" : "2012-10-17"
                        }
                        """.formatted(minioProperties.getBucketName());

                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(policy).build());
            }
            //原始的文件名字 比如：1.jpg
            String originalFilename = file.getOriginalFilename();

            //截取后缀名字
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));

            //拼接新的文件名字
            String fileName = UUID.randomUUID() + suffixName;

            /*
            * 上传文件
            * contentType：文件的类型
            * object：保存到桶中的文件名字
            * */
            minioClient.putObject(PutObjectArgs.builder().bucket(minioProperties.getBucketName())
                    .object(fileName).contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build());

            System.out.println("文件上传成功");

            return String.join("/", minioProperties.getEndpoint(), minioProperties.getBucketName(), fileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
